//
//  CLNetWorkingTool.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/10.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import AFNetworking

//枚举定义网络发送的请求方式
enum RequestType:Int{
    case GET
    case POST
}
//网络请求工具类
class CLNetWorkingTool:AFHTTPSessionManager {
    //创建単例工具
    static let sharedTool:CLNetWorkingTool = {
        let tools = CLNetWorkingTool()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
   
    //封装请求方法
    func request (type:RequestType,url:String,params:AnyObject?,callback:(response :AnyObject?,error :NSError?)->()){
        print(params)
        if type == .GET {
        GET(url, parameters: params, progress: nil, success: { (_ , response) -> Void in
            callback(response: response, error: nil)
            }, failure: { (_ , error ) -> Void in
            callback(  response: nil, error: error )
        })
        }else {
        POST(url, parameters: params, progress: nil, success: { (_,response) -> Void in
            callback(response: response, error: nil )
            }, failure: { (_, error) -> Void in
                callback(response: nil, error: error)
        })
    }
        
}
}
//OAuth 登录相关接口
extension CLNetWorkingTool {
    //通过授权码code获得accesstoken
    func requestAccessToken(code:String,callback:(response :AnyObject?,error :NSError?)->()) {
        //准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //准备参数
        /*
        client_id 	true 	string 	申请应用时分配的AppKey。
        client_secret 	true 	string 	申请应用时分配的AppSecret。
        grant_type 	true 	string 	请求的类型，填写authorization_code
        
        
        grant_type为authorization_code时
        
        必选 	类型及范围 	说明
        code 	true 	string 	调用authorize获得的code值。
        redirect_ur
        
        */
        let params = [
            "client_id":WeiboAppkey,
            "client_secret":weiboAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WeiboRedirect_ur
        ]
        //使用通用接口请求
        request(.POST, url: url, params: params, callback: callback)
    }
    //获取用户信息
    func requestUserInfo(userAccount :CLUserAccount,callback:(response :AnyObject?,error :NSError?) -> ())
    {
      //请求接口信息
        let url = "https://api.weibo.com/2/users/show.json"
        let params = [
        
            "access_token":userAccount.access_token!,
            "uid":"\(userAccount.uid)"
        
        ]
        request(.GET, url: url, params: params, callback: callback)
    }
  
    
}
  // MARK:  首页微博登录接口相关
extension CLNetWorkingTool {
    func loadStatus(maxId:Int64 = 0, sinceId:Int64 = 0, callback :(response :AnyObject?,error :NSError?)->()) {
        //准备接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let params = [
            "access_token" :CLUserAccountViewModel.sharedUserAccount.accesstoken!,
            "maxId":"\(maxId)",
            "sinceId":"\(sinceId)"
        ]
        request (.GET,url:url,params:params,callback:callback)
    }
    
    
}

//发送微博接口
extension CLNetWorkingTool {
    //发送文字接口
    func update(access_token:String,status:String,callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        //准备接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //准备参数
        let params = [
            "access_token":access_token,
            "status":status
         ]
        //网络请求
        request(.POST, url: url, params: params, callback: callBack)
    }
    
    //发送文字配图接口
    func upload(access_token:String,status:String,image:UIImage,callBack: (response: AnyObject?, error: NSError?) -> ()){
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token":access_token,
            "status":status
        ]
        //图片压缩成小格式的jpg  节省内存
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        //上传图片接口
        POST(url, parameters: params,constructingBodyWithBlock: {(formData ) -> Void in
            formData.appendPartWithFileData(imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            
            },progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error )
        }
        
    }
}


